package cn.hr.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.hr.pojo.*;
import cn.hr.service.DictionaryService;
import cn.hr.service.PostService;
import cn.hr.service.SalaryStandardService;
import cn.hr.utils.Constants;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.hr.service.ArchivesService;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.sql.SQLException;
import java.util.*;

/**
 * 人事档案控制器
 *
 * @author MO
 */

@Controller
@RequestMapping("/sys/archives")
public class ArchivesController {
    private Logger logger = LoggerFactory.getLogger(ArchivesController.class);
    @Resource
    private ArchivesService archivesService;
    @Resource
    private SalaryStandardService salaryStandardService;
    @Resource
    private DictionaryService dictionaryService;
    @Resource
    private PostService postService;
    @Resource
    private SolrClient solrClient;

    @RequestMapping("/add")
    public String add() {
        return "archives/add";
    }

    @RequestMapping("/addSave")
    //添加数据
    public String addSave(Archives archives, HttpSession session, HttpServletRequest request, @RequestParam(value = "attachs", required = false) MultipartFile[] attachs, @RequestParam Integer num) {
        String picturePath = null;
        String resumePath = null;
        String errorInfo = null;
        boolean flag = true;
        //String path = "D:/GitBoot/HRSystem_SpringBoot/src/main/resources" + File.separator + "static" + File.separator + "upload";
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadOcError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
                int filesize = 900000000;
                if (attach.getSize() > filesize) {//上传大小不得超过 500k
                    request.setAttribute(errorInfo, " * 上传大小不得超过 500k");
                    flag = false;
                } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg") || prefix.equalsIgnoreCase("zip")) {//上传图片格式
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + prefix;
                    logger.debug("new fileName======== " + attach.getName());
                    File targetFile = new File(Constants.BASEPATH, fileName);
                    if (!targetFile.exists()) {
                        targetFile.getParentFile().mkdirs();
                        try {
                            targetFile.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    //保存
                    try {
                        attach.transferTo(targetFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败！");
                        flag = false;
                    }
                    if (i == 0) {
                        resumePath = Constants.BASEPATH + File.separator + fileName;
                    } else if (i == 1) {
                        picturePath = Constants.BASEPATH + File.separator + fileName;
                    }
                    logger.debug("companyLicPicPath: " + picturePath);
                    logger.debug("orgCodePicPath: " + resumePath);
                } else {
                    request.setAttribute(errorInfo, " * 上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if (flag) {
            archives.setPicturePath(picturePath);
            archives.setResumePath(resumePath);
            archives.setAuditStatus(num);
            archives.setCreatedById(((SysUser) (session.getAttribute(Constants.USER_SESSION))).getId());
            archives.setCreatedDate(new Date());
            try {
                if (archivesService.insert(archives)) {
                    return "redirect:/sys/archives/archivesShow";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "redirect:/sys/archives/add";
    }

    @RequestMapping("/archivesList")
    public String list(@RequestParam(required = false) Map map, @RequestParam(defaultValue = "1") Integer pageNo, Model model) {
        PageInfo<Map> pageInfo = null;
        try {
            pageInfo = archivesService.findListByCondition(map, pageNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("pageInfo", pageInfo);
        return "archives/archivesShow";
    }

    @RequestMapping("/archivesShow")
    //主页数据显示跳转
    public String archivesShow() {
        return "archives/archivesList";
    }

    @RequestMapping("/update")
    //修改跳转页面
    public String getArchives(@RequestParam Integer id, @RequestParam Integer identified, Model model) {
        Archives archives = null;
        Post post = null;
        String fullName = null;
        try {
            archives = archivesService.get(id);
            post = postService.selectCode(archives.getPostId());
            fullName = postService.selectOFullName(archives.getPostId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("archives", archives);
        model.addAttribute("post", post);
        model.addAttribute("fullName", fullName);
        model.addAttribute("identified", identified);//区分变更与修改
        return "archives/archivesModify";
    }

    @RequestMapping("updateSave")
    //修改保存
    public String update(Archives archives, HttpSession session, HttpServletRequest request, @RequestParam(value = "attachs", required = false) MultipartFile[] attachs) {
        String picturePath = null;
        String resumePath = null;
        String errorInfo = null;
        boolean flag = true;
        //String path = "D:/GitBoot/HRSystem_SpringBoot/src/main/resources" + File.separator + "static" + File.separator + "upload";
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadOcError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
                System.out.println(oldFileName + prefix);
                int filesize = 500000;
                if (attach.getSize() > filesize) {//上传大小不得超过 500k
                    request.setAttribute(errorInfo, " * 上传大小不得超过 500k");
                    flag = false;
                } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg") || prefix.equalsIgnoreCase("zip")) {//上传格式
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + prefix;
                    logger.debug("new fileName======== " + attach.getName());
                    File targetFile = new File(Constants.BASEPATH, fileName);
                    if (!targetFile.exists()) {
                        targetFile.getParentFile().mkdirs();
                        try {
                            targetFile.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                            System.out.println("文件创建错误");
                        }
                    }
                    System.out.println("创建文件成功");
                    //保存
                    try {
                        attach.transferTo(targetFile);
                        System.out.println("上传文件成功");
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败！");
                        flag = false;
                    }
                    if (i == 0) {
                        picturePath = Constants.BASEPATH + File.separator + fileName;
                    } else if (i == 1) {
                        resumePath = Constants.BASEPATH + File.separator + fileName;
                    }
                    logger.debug("companyLicPicPath: " + picturePath);
                    logger.debug("orgCodePicPath: " + resumePath);
                } else {
                    request.setAttribute(errorInfo, " * 上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if (flag) {
            archives.setPicturePath(picturePath);
            archives.setResumePath(resumePath);
            archives.setModifyById(((SysUser) (session.getAttribute(Constants.USER_SESSION))).getId());
            archives.setModifyDate(new Date());
            try {
                if (archivesService.update(archives)) {
                    return "redirect:/sys/archives/archivesShow";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "redirect:/sys/archives//update";
    }

    @RequestMapping("/status")
    @ResponseBody
    //查询档案状态
    public Object Status() {
        try {
            return dictionaryService.selectAllByTypeName("STATUS_TYPE");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/auditStatus")
    @ResponseBody
    //查询审核状态
    public Object auditStatus() {
        try {
            return dictionaryService.selectAllByTypeName("AUDITSTATUS_TYPE");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/education")
    @ResponseBody
    //查询学历
    public Object education() {
        try {
            return dictionaryService.selectAllByTypeName("EDUCATION_TYPE");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/salS")
    @ResponseBody
    //查询薪资
    public Object salS() {
        return salaryStandardService.selectAllIdAndName();
    }

    @RequestMapping("/recover")
    @ResponseBody
    //恢复删除项
    public Object recover(@RequestParam Integer status, @RequestParam Integer id, HttpSession session) {
        Archives archives = new Archives();
        archives.setStatus(status);
        archives.setId(id);
        archives.setModifyById(((SysUser) (session.getAttribute(Constants.USER_SESSION))).getId());
        archives.setModifyDate(new Date());
        return archivesService.recover(archives);
    }

    @RequestMapping("/delete")
    @ResponseBody
    //删除数据
    public Object delete(@RequestParam Integer id) {
        try {
            return archivesService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @RequestMapping("/delFile")
    @ResponseBody
    //删除文件
    public Object delFile(@RequestParam Integer id, @RequestParam Integer distinguish) {
        Map<String, Object> result = new HashMap<>();
        if (id == null || id == 0) {
            result.put("result", "false");
        }
        try {
            if (archivesService.delFile(id, distinguish)) {
                result.put("result", "true");
            } else {
                result.put("result", "false");
            }
        } catch (SQLException e) {
            result.put("result", "false");
            e.printStackTrace();
        }
        return JSON.toJSONString(result);
    }


    //文件下载相关代码
    @RequestMapping("/downloadFile")
    public String downloadFile(@RequestParam("id") Integer id, HttpServletResponse response) {
        Archives archives = null;
        String fileName = null;
        try {
            archives = archivesService.selectPath(id, 1);
            fileName = archives.getName() + ".zip";
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (fileName != null) {
            File file = new File(archives.getResumePath());
            if (file.exists()) {
                response.setContentType("application/force-download");
                try {
                    response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("GBK"), "ISO8859-1"));//设置下载文件名
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("ok");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

    @RequestMapping("/changeType")
    @ResponseBody
    //变更类型
    public Object changeType() {
        try {
            return dictionaryService.selectAllByTypeName("CHANGE_TYPE");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/selectFullName")
    @ResponseBody
    //根据职位id查询部门名称
    public Object selectOFullName(@RequestParam Integer id) {
        return postService.selectOFullName(id);
    }

}
